<template>
  <div>
    <!-- 输入框和录入按钮开始 -->
    <div class="btns">

      <el-form :inline="true" :model="form" class="demo-form-inline">
        <el-row>
          <el-col :span="18">
            <el-form-item>
              <el-input v-model="form.user" placeholder="请输入工程名称"></el-input>
            </el-form-item>
            <el-form-item>
              <el-select v-model="form.region" placeholder="请选择工程状态">
                <el-option label="区域一" value="shanghai"></el-option>
                <el-option label="区域二" value="beijing"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search">搜索</el-button>
            </el-form-item>
          </el-col>
          <el-col :span="6" style="text-align: right;">
            <el-form-item>
              <el-button type="primary" @click="toAdd">录入</el-button>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
    </div>
    <!-- 输入框和录入按钮结束 -->
    <!-- 表格开始 -->
    <div class="table">
      <el-table :data="engData" border style="width: 100%">
        <el-table-column type="index" :index="1" label="序号" width="80" align="center">
        </el-table-column>
        <el-table-column prop="serial_number" label="编号" width="180" align="center">
        </el-table-column>
        <el-table-column prop="name" label="名称" width="360" align="center">
        </el-table-column>
        <el-table-column prop="type" label="工程类型" align="center">
          <template v-slot="scope">
            <div>
              <el-tag v-if="scope.row.type == '事业单位'">事业单位</el-tag>
              <el-tag v-else-if="scope.row.type == '写字楼'" type="warning">写字楼</el-tag>
              <el-tag v-else-if="scope.row.type == '园区'" type="danger">园区</el-tag>
              <el-tag v-else type="success">建筑工地</el-tag>
            </div>
          </template>

        </el-table-column>
        <el-table-column prop="create_time" label="开始时间" align="center">
          <!-- 作用域插槽  -->
          <template v-slot="scope">
            <div>{{ scope.row.create_time | fmtDate }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="end_time" label="结束时间" align="center">
          <template v-slot="scope">
            <div>{{ scope.row.end_time == null ? "未结束" : moment(scope.row.end_time).format('YYYY-MM-DD:HH:mm:ss') }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" align="center">
          <template v-slot="scope">
            <div>
              <el-tag v-if="scope.row.status == '监测中'" effect="dark" type="success">监测中</el-tag>
              <el-tag v-else-if="scope.row.status == '未绑定'" effect="dark" type="warning">未绑定</el-tag>
              <el-tag v-else effect="dark" type="danger">已结束</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template v-slot="scope">
            <div>
              <el-link @click="toEdit(scope.row)" :underline="false" type="success">修改</el-link>
              <el-link @click="toBind(scope.row)" :disabled="scope.row.status == '已结束'" :underline="false" type="primary">绑定</el-link>
              <el-link @click="toFinish(scope.row.id)"
                :disabled="scope.row.status == '已结束' || scope.row.status == '未绑定'" :underline="false"
                type="danger">结束</el-link>
              <el-link @click="toDelete(scope.row.id)"
                :disabled="scope.row.status == '已结束' || scope.row.status == '监测中'" :underline="false"
                type="warning">删除</el-link>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 表格结束 -->
    <!-- 分页开始 -->
    <div class="page" style="margin-top: 10px;">
      <el-pagination hide-on-single-page @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="params.page" :page-sizes="[5, 8, 10, 20]" :page-size="params.pageSize"
        layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>
    <!-- 分页结束 -->
    <!-- 抽屉 -->
    <el-drawer @close="reset" size="50%" :title="title" :visible.sync="visible" direction="rtl" custom-class="demo-drawer"
      ref="drawer">
      <div class="demo-drawer__content" style="padding-right: 10px;">
        {{ this.formSave }}
        <el-form :rules="rules" ref="myForm" :model="formSave">
          <el-row>
            <el-col :span="12">
              <el-form-item prop="serial_number" label="工程编号" :label-width="formLabelWidth">
                <el-input class="input" clearable placeholder="请输入工程编号" v-model="formSave.serial_number"
                  autocomplete="off"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="name" label="工程名称" :label-width="formLabelWidth">
                <el-input class="input" clearable placeholder="请输入工程名称" v-model="formSave.name"
                  autocomplete="off"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="type" label="工程类型" :label-width="formLabelWidth">
                <el-select clearable class="select" v-model="formSave.type" placeholder="请选择工程类型">
                  <el-option label="写字楼" value="写字楼"></el-option>
                  <el-option label="事业单位" value="事业单位"></el-option>
                  <el-option label="园区" value="园区"></el-option>
                  <el-option label="建筑工地" value="建筑工地"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="charge_id" label="区域经理" :label-width="formLabelWidth">
                <el-select clearable class="select" v-model="formSave.charge_id" placeholder="请选择区域经理">
                  <el-option v-for="item in manager" :key="item.id" :label="item.realname" :value="item.id"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="工程经度" :label-width="formLabelWidth">
                <el-input clearable class="input" placeholder="请输入工程经度" v-model="formSave.longitude"
                  autocomplete="off"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="工程纬度" :label-width="formLabelWidth">
                <el-input clearable class="input" placeholder="请输入工程纬度" v-model="formSave.latitude"
                  autocomplete="off"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="工程地址" :label-width="formLabelWidth">
                <el-cascader v-model="formSave.address1" placeholder="请选择工程地址" class="select" :options="pca"
                  :props="{ label: 'name', value: 'name' }" clearable></el-cascader>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="详细地址" :label-width="formLabelWidth">
                <el-input clearable class="input" placeholder="请输入详细地址" v-model="formSave.address"
                  autocomplete="off"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="title == '修改工程信息'">
              <el-form-item label="客户名称" :label-width="formLabelWidth">
                <el-select clearable class="select" v-model="formSave.customer_name" placeholder="请选择客户">
                  <el-option v-for="item in customer" :key="item.id" :label="item.realname"
                    :value="item.id"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12" v-else>
              <el-form-item label="客户名称" :label-width="formLabelWidth">
                <el-input clearable class="input" placeholder="请输入客户名称" v-model="formSave.customer_name"
                  autocomplete="off"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="客户电话" :label-width="formLabelWidth">
                <el-input clearable class="input" placeholder="请输入客户电话" v-model="formSave.customer_telephone"
                  autocomplete="off"></el-input>
              </el-form-item>
            </el-col>
          </el-row>


        </el-form>
        <div class="demo-drawer__footer">
          <el-button @click="visible = false">取 消</el-button>
          <el-button type="primary" @click="toSubmit">确定</el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>
<script>
import { get, del, post,postJSON } from '@/utils/request'
import moment from 'moment'
// 引入省市区数据
import pca from '@/assets/pca.json'
// 引入lodash工具库 
import _ from 'lodash';
export default {
  data() {
    return {
      pca,
      // 表单数据对象 
      form: {},
      // 表格显示的数据 
      engData: [],
      params: {
        page: 1,
        pageSize: 5
      },
      // 数据总条数 
      total: 0,
      // 抽屉标题 
      title: '录入工程信息',
      // 控制抽屉显示与隐藏 
      visible: false,
      // 录入和修改表单数据对象 
      formSave: {},
      // 表单标签域宽度 
      formLabelWidth: '90px',
      // 区域经理 
      manager: [],
      // 客户 
      customer: [],
      // 表单验证规则 
      rules: {
        serial_number: [
          { required: true, message: '请输入工程编号', trigger: "blur" },
        ],
        name: [
          { required: true, message: '请输入工程名称', trigger: "blur" },
        ],
        type: [
          { required: true, message: '请选择工程类型', trigger: "change" },
        ],
        charge_id: [
          { required: true, message: '请选择区域经理', trigger: "change" },
        ]
      }
    }
  },
  methods: {
    // 去绑定 
    toBind(row){
      // 跳转到工程详情页面 编程式路由导航 
      this.$router.push({
        path:'/am/engineer/Details',
        query:row
      })
      
    },
    // 模态框关闭前重置表单校验 
    reset(){
      this.$refs['myForm'].resetFields();
    },
    // 去保存或者新增工程信息

    toSubmit() {
      this.$refs['myForm'].validate(async (valid) => {
        if (valid) {
          // 表单校验通过  发起保存或者更新请求 
          // alert('submit!');
          // console.log(this.formSave);
          let data = _.clone(this.formSave);
          data.address = data.address1.join(' ') + ' ' + data.address;
          delete data.address1;
          console.log(data, '-------------');
          let res = await postJSON ('/engineer/saveOrUpdate', data);
          if (res.status == 200) {
            this.$notify({
              title: "成功",
              message: res.message,
              type: 'success'
            });
            this.visible = false;
            // 重新查询数据
            this.getEngData();
          } else {
            return false;
          }
        } else {
          // 表单校验失败
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 修改工程信息  
    toEdit(row) {
      this.visible = true;
      this.title = '修改工程信息';
      // ...拓展运算符  展开当前行对象
      // this.formSave = {...row};
      this.formSave = _.clone(row);
      this.formSave.address1 = this.formSave.address.split(' ').slice(0, 3);
      this.formSave.address = this.formSave.address.split(' ').slice(3).join(' ');

    },
    // 录入工程信息 
    toAdd() {
      // 抽屉显示
      this.visible = true;
      // 修改标题 
      this.title = "录入工程信息";
      // 清空表单数据对象 
      this.formSave = {};
    },
    // 查询所有客户 
    async queryCustomers() {
      let res = await get("/user/pageQuery", { page: 1, pageSize: 1000, role_id: 4 });
      console.log(res, '客户');
      this.customer = res.data.list;
    },
    // 查询所有区域经理 
    async queryEngData() {
      let res = await get("/user/pageQuery", { page: 1, pageSize: 1000, role_id: 3 });
      // console.log(res, '区域经理');
      this.manager = res.data.list;
    },
    // 去删除工程 
    toDelete(id) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        // 点了确定按钮 发起删除工程请求 
        let res = await del('/engineer/deleteById', { id });
        this.$message({
          type: 'success',
          message: '操作成功!'
        });
        // 从第一页重新载入数据 
        this.params.page = 1;
        // 重新载入数据 
        this.getEngData();
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消操作'
        });
      });
    },
    // 结束工程 
    toFinish(id) {
      // console.log(id);
      this.$confirm('此操作将永久结束该工程, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        // 点了确定按钮 发起结束工程请求 
        let res = await get('/engineer/finish', { id });
        this.$message({
          type: 'success',
          message: '操作成功!'
        });
        // 重新载入数据 
        this.getEngData();
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消操作'
        });
      });
    },
    moment,
    // 每页条数发生改变就会触发 
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`); //val 2条/页--->5条/页 val-->5
      this.params.pageSize = val;
      this.getEngData();
    },
    // 页码发生改变就会触发 
    handleCurrentChange(val) {
      // val表示就是页码 1-->3 
      // console.log(`当前页: ${val}`); 1 2 3
      this.params.page = val;
      // 重新查询数据 
      this.getEngData();
    },
    // 获取工程数据方法 
    async getEngData() {

      let res = await get('/engineer/pageQuery', this.params);
      console.log(res, '获取响应');
      this.engData = res.data.list;
      this.total = res.data.total;
    }
  },
  // 最早的异步请求 
  created() {
    this.getEngData();
    this.queryEngData();
    this.queryCustomers();
  }
}
</script>
<style lang="scss" scoped>
// vue2深度选择器   
::v-deep .el-link--inner {
  margin-left: 5px;
}

.input {
  width: 280px;
}

.select {
  width: 280px;
}

.demo-drawer__footer {
  border-top: 1px solid #ececec;
  padding-top: 10px;
  position: fixed;
  bottom: 50px;
  width: 50%;
  text-align: center;
}
</style>